package com.chyb.cloud.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;


@RestController
@Slf4j
public class EmpowerController {
    @GetMapping(value = "/empower")
    public String requestSentinel4() {
        log.info("测试Sentinel授权规则empower");
        return "Sentinel授权规则";
    }


    @GetMapping(value = "/testIp")
    public String testIp(HttpServletRequest request) {
        // 单行代码实现
        String ipv4 = Optional.ofNullable(request.getHeader("X-Forwarded-For"))
                .orElse(request.getRemoteAddr()) // 无代理时回退到 remoteAddr
                .split(",")[0].trim()           // 取第一个 IP（防止多代理链）
                .replace("::ffff:", "");        // 清理 IPv6 映射格式

        // 本地 IPv6 转 IPv4
        if (ipv4.equals("0:0:0:0:0:0:0:1") || ipv4.equals("::1")) {
            ipv4 = "127.0.0.1";
        }

        log.info("Your IPv4: {}" , ipv4);
        return "Your IPv4: " + ipv4;
    }
}
